"use client";

import { useState, useEffect } from "react";
import { motion } from "framer-motion";
import { useRouter } from "next/navigation";
import {
  FiStar,
  FiList,
  FiGrid,
  FiSearch,
  FiTag,
  FiClock,
} from "react-icons/fi";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

// 模拟收藏数据
const mockFavorites = [
  {
    id: 1,
    title: "系统设计文档",
    author: "张三",
    addedAt: "2023-10-15",
    category: "技术",
    tags: ["设计", "架构"],
    description: "包含系统整体架构设计和关键组件的技术详情",
  },
  {
    id: 2,
    title: "用户手册",
    author: "李四",
    addedAt: "2023-10-14",
    category: "文档",
    tags: ["用户", "指南"],
    description: "详细的用户操作指南和常见问题解答",
  },
  {
    id: 3,
    title: "API文档",
    author: "王五",
    addedAt: "2023-10-13",
    category: "技术",
    tags: ["API", "开发"],
    description: "所有API接口的详细说明和使用示例",
  },
  {
    id: 4,
    title: "产品规划",
    author: "赵六",
    addedAt: "2023-10-12",
    category: "产品",
    tags: ["规划", "路线图"],
    description: "未来6个月的产品开发规划和功能迭代计划",
  },
  {
    id: 5,
    title: "团队协作指南",
    author: "孙七",
    addedAt: "2023-10-11",
    category: "团队",
    tags: ["协作", "流程"],
    description: "团队协作的最佳实践和工作流程指南",
  },
  {
    id: 6,
    title: "市场分析报告",
    author: "周八",
    addedAt: "2023-10-10",
    category: "市场",
    tags: ["分析", "报告"],
    description: "行业市场趋势分析和竞品调研报告",
  },
];

// 获取所有可用标签
const allTags = Array.from(new Set(mockFavorites.flatMap((item) => item.tags)));

export default function FavoritesPage() {
  const router = useRouter();
  const [favorites, setFavorites] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [selectedTag, setSelectedTag] = useState("all");

  useEffect(() => {
    // 检查登录状态
    const isLoggedIn = localStorage.getItem("isLoggedIn");
    if (!isLoggedIn) {
      router.push("/login");
      return;
    }

    // 模拟API加载数据
    setTimeout(() => {
      setFavorites(mockFavorites);
      setIsLoading(false);
    }, 1000);

    // 实际应用中应该通过API获取收藏数据
    // async function fetchFavorites() {
    //   try {
    //     const response = await fetch('/api/favorites');
    //     const data = await response.json();
    //     setFavorites(data);
    //   } catch (error) {
    //     console.error('获取收藏失败:', error);
    //   } finally {
    //     setIsLoading(false);
    //   }
    // }
    // fetchFavorites();
  }, [router]);

  const fadeIn = {
    hidden: { opacity: 0, y: 20 },
    visible: { opacity: 1, y: 0 },
  };

  // 筛选收藏项
  const filteredFavorites = favorites.filter((item) => {
    const matchesSearch =
      item.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      item.description.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesCategory =
      selectedCategory === "all" || item.category === selectedCategory;
    const matchesTag = selectedTag === "all" || item.tags.includes(selectedTag);

    return matchesSearch && matchesCategory && matchesTag;
  });

  // 获取所有可用分类
  const categories = Array.from(
    new Set(favorites.map((item) => item.category))
  );

  if (isLoading) {
    return (
      <div className='flex justify-center items-center h-[80vh]'>
        <div className='animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-blue-500'></div>
      </div>
    );
  }

  return (
    <div className='container mx-auto px-4 py-8'>
      {/* 页面标题 */}
      <motion.div
        className='text-center mb-10'
        initial='hidden'
        animate='visible'
        variants={fadeIn}
        transition={{ duration: 0.5 }}
      >
        <h1 className='text-4xl font-bold bg-gradient-to-r from-yellow-500 to-amber-600 text-transparent bg-clip-text mb-4'>
          我的收藏
        </h1>
        <p className='text-lg text-gray-600 dark:text-gray-300'>
          集中管理您收藏的重要文档和知识
        </p>
      </motion.div>

      {/* 搜索和筛选 */}
      <motion.div
        className='mb-8'
        initial='hidden'
        animate='visible'
        variants={fadeIn}
        transition={{ duration: 0.5, delay: 0.2 }}
      >
        <div className='grid grid-cols-12 gap-4'>
          <div className='col-span-12 md:col-span-6 lg:col-span-8 relative'>
            <FiSearch className='absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400' />
            <Input
              placeholder='搜索收藏...'
              className='pl-10 w-full'
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>

          <div className='col-span-6 md:col-span-3 lg:col-span-2'>
            <Select
              value={selectedCategory}
              onValueChange={setSelectedCategory}
              className='w-full'
            >
              <SelectTrigger className='w-full'>
                <SelectValue placeholder='选择分类' />
              </SelectTrigger>
              <SelectContent className='w-full'>
                <SelectItem value='all'>所有分类</SelectItem>
                {categories.map((category) => (
                  <SelectItem key={category} value={category}>
                    {category}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className='col-span-6 md:col-span-3 lg:col-span-2'>
            <Select
              value={selectedTag}
              onValueChange={setSelectedTag}
              className='w-full'
            >
              <SelectTrigger className='w-full'>
                <SelectValue placeholder='选择标签' />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value='all' className='w-full'>
                  所有标签
                </SelectItem>
                {allTags.map((tag) => (
                  <SelectItem key={tag} value={tag}>
                    {tag}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </div>
      </motion.div>

      {/* 内容显示 */}
      <motion.div
        initial='hidden'
        animate='visible'
        variants={fadeIn}
        transition={{ duration: 0.5, delay: 0.4 }}
      >
        <Tabs defaultValue='grid' className='w-full'>
          <div className='flex justify-between items-center mb-6'>
            <div className='text-lg font-medium'>
              共 {filteredFavorites.length} 个收藏项
            </div>
            <TabsList>
              <TabsTrigger value='grid'>
                <FiGrid className='mr-2' />
                卡片视图
              </TabsTrigger>
              <TabsTrigger value='list'>
                <FiList className='mr-2' />
                列表视图
              </TabsTrigger>
            </TabsList>
          </div>

          {/* 卡片视图 */}
          <TabsContent value='grid'>
            <div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6'>
              {filteredFavorites.map((item) => (
                <Card
                  key={item.id}
                  className='hover:shadow-md transition-shadow'
                >
                  <CardHeader>
                    <div className='flex justify-between items-start'>
                      <CardTitle className='text-xl text-blue-600 dark:text-blue-400'>
                        {item.title}
                      </CardTitle>
                      <FiStar className='text-yellow-500' size={20} />
                    </div>
                  </CardHeader>
                  <CardContent>
                    <p className='text-gray-600 dark:text-gray-300 text-sm mb-4'>
                      {item.description}
                    </p>
                    <div className='flex flex-wrap gap-2 mb-2'>
                      {item.tags.map((tag) => (
                        <Badge
                          key={tag}
                          variant='outline'
                          className='bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 hover:bg-blue-100'
                        >
                          <FiTag className='mr-1' size={12} />
                          {tag}
                        </Badge>
                      ))}
                    </div>
                    <p className='text-gray-500 dark:text-gray-400 text-xs'>
                      <FiClock className='inline mr-1' size={12} />
                      收藏于: {item.addedAt}
                    </p>
                  </CardContent>
                  <CardFooter className='border-t pt-4 flex justify-between'>
                    <span className='text-sm text-gray-500'>
                      作者: {item.author}
                    </span>
                    <Button size='sm' variant='outline'>
                      查看文档
                    </Button>
                  </CardFooter>
                </Card>
              ))}
            </div>
          </TabsContent>

          {/* 列表视图 */}
          <TabsContent value='list'>
            <div className='bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden'>
              <div className='overflow-x-auto'>
                <table className='min-w-full'>
                  <thead>
                    <tr className='bg-gray-50 dark:bg-gray-750 border-b border-gray-200 dark:border-gray-700'>
                      <th className='px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400'>
                        文档名称
                      </th>
                      <th className='px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400'>
                        分类
                      </th>
                      <th className='px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400'>
                        标签
                      </th>
                      <th className='px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400'>
                        作者
                      </th>
                      <th className='px-4 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400'>
                        收藏日期
                      </th>
                      <th className='px-4 py-3 text-right text-sm font-medium text-gray-500 dark:text-gray-400'>
                        操作
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredFavorites.map((item) => (
                      <tr
                        key={item.id}
                        className='border-b border-gray-100 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-750'
                      >
                        <td className='px-4 py-4 text-blue-600 dark:text-blue-400 font-medium'>
                          <div className='flex items-center'>
                            <FiStar
                              className='text-yellow-500 mr-2'
                              size={16}
                            />
                            {item.title}
                          </div>
                        </td>
                        <td className='px-4 py-4 text-gray-600 dark:text-gray-300'>
                          {item.category}
                        </td>
                        <td className='px-4 py-4'>
                          <div className='flex flex-wrap gap-1'>
                            {item.tags.map((tag) => (
                              <Badge
                                key={tag}
                                variant='outline'
                                className='bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
                              >
                                {tag}
                              </Badge>
                            ))}
                          </div>
                        </td>
                        <td className='px-4 py-4 text-gray-600 dark:text-gray-300'>
                          {item.author}
                        </td>
                        <td className='px-4 py-4 text-gray-500 dark:text-gray-400'>
                          {item.addedAt}
                        </td>
                        <td className='px-4 py-4 text-right'>
                          <Button size='sm' variant='ghost'>
                            查看
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </TabsContent>
        </Tabs>

        {filteredFavorites.length === 0 && (
          <div className='py-16 text-center'>
            <div className='inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 dark:bg-gray-800 mb-4'>
              <FiStar className='text-gray-400' size={24} />
            </div>
            <h3 className='text-lg font-medium text-gray-900 dark:text-gray-100 mb-2'>
              没有找到匹配的收藏项
            </h3>
            <p className='text-gray-500 dark:text-gray-400'>
              尝试调整搜索条件或清除筛选器
            </p>
          </div>
        )}
      </motion.div>
    </div>
  );
}
